package com.example.jegotrip;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.MenuItem;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.PackageManagerCompat;
import androidx.fragment.app.FragmentTransaction;

import com.example.jegotrip.fragment.home.HomeFragment;
import com.example.jegotrip.fragment.mine.MineFragment;
import com.example.jegotrip.fragment.order.OrderFragment;
import com.example.jegotrip.fragment.search.SearchFragment;
import com.example.jegotrip.base.BaseActivity;
import com.example.jegotrip.fragment.shop.ShoppingFragment;
import com.example.jegotrip.utils.CustomToast;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends BaseActivity {

    private HomeFragment homeFragment;
    private ShoppingFragment shoppingFragment;
    private OrderFragment orderFragment;
    private SearchFragment searchFragment;
    private MineFragment mineFragment;
//请求位置权限的请求码100
    private static final int REQUEST_CODE = 100;

    private BottomNavigationView bottomNavigationView;
    @Override
    protected void initData() {

        selectedFragment(0);// 默认选中首页

        requestLocationPermissions();

        checkNetworkIsAvailable();
    }

    /**
     * 检测网络是否可用
     */
    private void checkNetworkIsAvailable() {
        // 网络请求在单独的线程中执行
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL("http//:www.baidu.com");
                            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

                    StringBuilder result = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }
                    reader.close();

                    // 更新UI，显示结果
                    final String response = result.toString();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            CustomToast.showCenterToast(MainActivity.this,response);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void requestLocationPermissions() {
//        请求位置权限
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE){
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                // Permission granted ,proceed with Location_related operations :位置未授权，进行相应的处理
                // 请求权限
                requestLocationPermissions();
            } else {
                // Permission denied ,handle accordingly：已授权。进行相应的操作

            }
        }
    }

    @Override
    protected void setListener() {
        /**
         * BottomNavigationView的默认背景中包含了这个指示灯的问题。所以解决方案除了在代码中设置外，还可以直接修改默认主题解决
         */
        bottomNavigationView.setItemActiveIndicatorEnabled(false);
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                if (item.getItemId() == R.id.home) {
                    selectedFragment(0);
                } else if (item.getItemId() == R.id.shop) {
                    selectedFragment(1);
                } else if (item.getItemId() == R.id.order) {
                    selectedFragment(2);
                } else if (item.getItemId() == R.id.search) {
                    selectedFragment(3);
                } else if (item.getItemId() == R.id.mine) {
                    selectedFragment(4);
                }
                return true;
            }
        });
    }

    @Override
    protected void initViews() {

        bottomNavigationView = findViewById(R.id.bottomNavigationView);
//        这行代码设置所有tab图标灰色
//        bottomNavigationView.setItemIconTintList(null);

        /**
         * 文字的动态更改
         *
         * 文字颜色的动态更改需要通过Java代码来实现。
         * 首先，获取资源文件中定义的颜色状态列表，然后使用setItemTextColor方法设置文字颜色：
         */
        Resources resource = getResources();
        @SuppressLint({"ResourceType", "UseCompatLoadingForColorStateLists"}) ColorStateList csl = resource.getColorStateList(R.drawable.bottom_btn_selected_color);
        bottomNavigationView.setItemTextColor(csl);
    }

    @Override
    protected int getLayoutResOId() {
        return R.layout.activity_main;
    }

    private void selectedFragment(int position){
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        hideFragment(fragmentTransaction);

        if (position == 0){
            if (homeFragment == null) {
                homeFragment = new HomeFragment();
                fragmentTransaction.add(R.id.content, homeFragment);
            } else {
                fragmentTransaction.show(homeFragment);
            }
        } else if (position == 1){
            if (shoppingFragment == null) {
                shoppingFragment = new ShoppingFragment();
                fragmentTransaction.add(R.id.content, shoppingFragment);
            } else {
                fragmentTransaction.show(shoppingFragment);
            }
        } else if (position == 2){
            if (orderFragment == null) {
                orderFragment = new OrderFragment();
                fragmentTransaction.add(R.id.content, orderFragment);
            } else {
                fragmentTransaction.show(orderFragment);
            }
        } else if (position == 3){
            if (searchFragment == null) {
                searchFragment = new SearchFragment();
                fragmentTransaction.add(R.id.content, searchFragment);
            } else {
                fragmentTransaction.show(searchFragment);
            }
        } else if (position == 4){
            if (mineFragment == null) {
                mineFragment = new MineFragment();
                fragmentTransaction.add(R.id.content, mineFragment);
            } else {
                fragmentTransaction.show(mineFragment);
            }
        }
        fragmentTransaction.commit();
        // 一定要提交
    }

    private void hideFragment(FragmentTransaction fragmentTransaction) {
        if (homeFragment != null) {
            fragmentTransaction.hide(homeFragment);
        }

        if (shoppingFragment != null) {
            fragmentTransaction.hide(shoppingFragment);
        }

        if (orderFragment != null) {
            fragmentTransaction.hide(orderFragment);
        }

        if (searchFragment != null) {
            fragmentTransaction.hide(searchFragment);
        }

        if (mineFragment != null) {
            fragmentTransaction.hide(mineFragment);
        }
    }
}
